package com.blog.controller;

import com.blog.common.ServerResponse;
import com.blog.pojo.User;
import com.blog.service.IUserService;
import com.blog.exception.MyException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;



/**
 * @author
 * @create 2018-06-04 15:09
 **/
@Controller
@RequestMapping("/admin/")
public class UserController {

    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private IUserService iUserService;

    @RequestMapping("index.action")
    public String index() {

        return "admin/index";
    }



    @RequestMapping("login.action")
    public String login() {

        return "admin/login";
    }

    @RequestMapping("register.action")
    public String register() {
        System.out.println("111");
        return "admin/register";
    }


    @RequestMapping("login.json")
    @ResponseBody
    public ServerResponse login2(ModelMap map, HttpServletRequest request) throws MyException {
        log.debug("登录开始");
        log.info("info登录开始");
        log.error("error登录开始");
        //0 获取参数
        String loginName = request.getParameter("login_name");
        String passWord = request.getParameter("pass_word");
        //1 判断参数是否为空
        if (StringUtils.isEmpty(loginName) || StringUtils.isEmpty(passWord)) {
            throw new MyException("用户名、密码不能为空");
        }
        //2 判断用户名和密码是否正确
        User user = iUserService.checkUser(loginName, passWord);
        if (user == null) {

//            throw new MyException("用户名不存在");
            return ServerResponse.error("用户不存在");
        }

        //设置session
        request.getSession().setAttribute("user", user);
        if(user.getLoginName()== "admin" && user.getPassWord() =="admin"){
            return ServerResponse.success();
        }else {
            return ServerResponse.error();
        }
    }

    @RequestMapping("logOut.action")
    public String logOut(HttpServletRequest request) {
        //1 删除session
        request.getSession().invalidate();
        return "admin/login";
    }
}
